package com.bw.auth.config;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.bw.auth.domain.SysUser;
import com.bw.auth.domain.SysUserOnline;
import com.bw.auth.service.SysUserService;
import com.ruoyi.common.core.domain.R;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Component
@Aspect
public class UserOnlineAop {
    @Pointcut("execution(* com.bw.auth.controller.AuthController.login(..))")
    public void pt() {
    }
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    RedisTemplate redisTemplate;

    @Around("pt()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取用户
        Integer uid = (Integer) redisTemplate.opsForValue().get("uid");
        SysUser sysUser = sysUserService.getById(uid);
//      获取路径切割数组
        String[] path = request.getServletPath().split("/");
//      判断该路径是否以user开头,float:拦截,反之放行
        if (path!=null) {
            if (path[2].equals("login")) {
                System.err.println(path[1] + " : " + "放行");
                R result = (R) joinPoint.proceed();
                if (result.getCode() == 200) {
                    //存redis
                    //用户名
                    Object[] args = joinPoint.getArgs();
                    SysUser user = (SysUser) args[0];
                    String uname = user.getUname();

                    LambdaQueryWrapper<SysUser> sysUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    sysUserLambdaQueryWrapper.eq(SysUser::getUname, uname);
                    SysUser one = sysUserService.getOne(sysUserLambdaQueryWrapper);

                    SysUserOnline sysUserOnline = new SysUserOnline();
                    sysUserOnline.setIp(request.getRemoteAddr());
                    sysUserOnline.setTel(one.getTel());
                    sysUserOnline.setUname(uname);
                    sysUserOnline.setCreateDate(new Date());
                    sysUserOnline.setId(one.getId());
                    String s = JSON.toJSONString(sysUserOnline);
                    redisTemplate.opsForValue().set("userolines:" + sysUserOnline.getId(), s);
                    return result;
                }
            }

        }
        return joinPoint.proceed();
    }


}
